package com.coffee.price.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.util.TypedValue;

/**
 * 도시락 유틸 클래스
 * 
 * 범용적인 기능을 지원하는 클래스로 도시락에서 활용되는 다양한 값을 불러오거나 연산하는 역할을 담당함
 */
public class Util {
	private static final String LOG_TAG = Util.class.getSimpleName();

	static final int ERROR = -1;

	
	/**
	 * 대상 호스트의 접속 가능 여부 판단
	 */
	public static boolean isReachableTargetHost(String sTargetHost, int nTimeOut) {
		boolean bRtn = false;

		if (0 >= nTimeOut)
			nTimeOut = 3000; // 3second

		try {
			bRtn = InetAddress.getByName(sTargetHost).isReachable(nTimeOut);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return bRtn;
	}

	/**
	 * 대상 호스트의 IP 어드레스 얻어오기
	 * 
	 * @param sTargetHost
	 * @return
	 */
	public static String getHost2IpAddress(String sTargetHost) {
		String sRtn = null;

		try {
			sRtn = InetAddress.getByName(sTargetHost).getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return sRtn;
	}

	/**
	 * 호스트 정보 얻어오기
	 * 
	 * @return
	 */
	public static String getMyHostAddress() {
		String sRtn = null;
		try {
			Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>) NetworkInterface
					.getNetworkInterfaces();
			while (e1.hasMoreElements()) {
				NetworkInterface ni = e1.nextElement();

				Enumeration<InetAddress> e2 = ni.getInetAddresses();
				while (e2.hasMoreElements()) {
					InetAddress ia = e2.nextElement();

					if (false == "127.0.0.1".equals(ia.getHostAddress())) {
						sRtn = ia.getHostAddress();
					}
				}
			}
		} catch (Exception e) {
			Log.d(Util.LOG_TAG, e.toString());
		}

		return sRtn;
	}

	
	/**
	 * Package설치 여부 판단
	 * 
	 * @param context
	 * @param pkgName
	 * @return
	 */
	public static boolean isPackageAlreadyInstalled(Activity context,
			String pkgName) {
		List<PackageInfo> installedList = context.getPackageManager()
				.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
		int installedListSize = installedList.size();
		for (int i = 0; i < installedListSize; i++) {
			PackageInfo tmp = installedList.get(i);
			if (pkgName.equalsIgnoreCase(tmp.packageName)) {
				return true;
			}

		}
		return false;
	}

	/**
	 * 네트윅이 사용 가능한 상태인가 확인
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			Log.w(Util.LOG_TAG, "couldn't get connectivity manager");
		} else {
			
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			//네트워크에 연결되었음.
			if (info != null && info.getState() == NetworkInfo.State.CONNECTED) {
				return true;
			}
		}
		return false;
	}

	/**
	 * WIFI사용중?
	 */
	public static boolean isWifi(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			Log.w(Util.LOG_TAG, "couldn't get connectivity manager");
		} else {
			NetworkInfo info = connectivity.getActiveNetworkInfo();

			if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI)
				return true;
		}

		return false;
	}

	/**
	 * MOBILE사용중?
	 */
	public static boolean isMobile(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			Log.w(Util.LOG_TAG, "couldn't get connectivity manager");
		} else {
			NetworkInfo info = connectivity.getActiveNetworkInfo();

			if (info != null
					&& info.getType() == ConnectivityManager.TYPE_MOBILE)
				return true;
		}

		return false;
	}
	
	/**
	 * <pre>
	 * dip -> px 변환
	 * @param number
	 * @return
	 * int
	 * </pre>
	 */
	public static int dipToInt(float number , Context ctx) {
	    int num = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, number,
	                ctx.getResources().getDisplayMetrics());
	    return num;
	}
	
    public static int stringToInt(String str, int defaultValue) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }
    
    public static String noticeIsRead(Context ctx){
    	
    	BufferedReader br = null;
    	String line = "";
    	try{
    		
    		br = new BufferedReader(new InputStreamReader(ctx.openFileInput("notice_isread.txt")));
    		line = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
    		try{if(br!=null)br.close();}catch(Exception e){}
    	}
		return line;
    }
    
    public static void noticeReadWrite(Context ctx , String date){
    	
    	BufferedWriter bw = null;
    	
    	try {
    		
    		bw = new BufferedWriter(new OutputStreamWriter(ctx.openFileOutput("notice_isread.txt",Context.MODE_PRIVATE)));
			bw.write(date+",Y");
			bw.close();
		
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try{if(bw!=null)bw.close();}catch(Exception e){}
		}
    }
    
	public static void LOG(String msg){
		
		FileOutputStream fos = null;
		
		try{
			fos = new FileOutputStream(new File("/sdcard/debug/log.txt"), true);
			fos.write(msg.getBytes());
			fos.flush();
			
		}catch(Exception e){
		}
		finally{
			try{ fos.close();}catch(Exception e){}
		}
		
	}
}
